import { Loading as LoadingNut } from '@nutui/nutui-react';
import { debounce } from 'lodash-es';
import { createRoot, Root } from 'react-dom/client';
interface Props {
  visible: boolean;
}

export const Loading = () => {
  return (
    <div className="fixed left-0 top-0 z-[99999] h-full w-full">
      <div className="fixed left-1/2 top-1/2 -translate-x-2/4 -translate-y-2/4 rounded-xl bg-[rgba(0,0,0,0.6)] p-5 ">
        <LoadingNut color="#fff" direction="vertical">
          <div className="text-white">加载中</div>
        </LoadingNut>
      </div>
    </div>
  );
};

let div: HTMLDivElement | null = null;
let loading = false;
let root: Root | null = null;

Loading.show = (props?: Props) => {
  if (loading) return;
  div = document.createElement('div');
  div.id = 'loading';
  document.body.appendChild(div);
  document.body.classList.add('disable-page-scroll');
  loading = true;
  setTimeout(() => {
    root = createRoot(document.getElementById('loading') as HTMLElement);
    root.render(<Loading {...props} />);
  });
};

Loading.hide = debounce(() => {
  if (!div) return;
  if (div.parentNode) {
    div.parentNode.removeChild(div);
    document.body.classList.remove('disable-page-scroll');
    div = null;
    loading = false;
  }
}, 200);

Loading.defaultProps = {
  visible: true
};
